package datastructure.str;


/**
 * @Author yao.xiao
 * @Date 2025/8/20 15:06
 * @Description 反转字符串2
 */
public class LC541 {
    public String reverseStr(String s, int k) {
        char[] charArray = s.toCharArray();
        int count = 0;
        int end = -1;
        for (int i = 0; i < charArray.length; i++) {
            count++;
            if (count == 2 * k) {
                int left = i - 2 * k + 1;
                int right = i - k;
                swap(left, right, charArray);
                count = 0;
                end = i;
            }
        }
        if (count == 0) {
            return String.valueOf(charArray);
        }
        int left = end + 1;
        int right = count < k ? charArray.length-1 : end + k;
        swap(left, right, charArray);
        return String.valueOf(charArray);
    }

    private void swap(int left, int right, char[] charArray) {
        while (left < right) {
            char temp = charArray[left];
            charArray[left] = charArray[right];
            charArray[right] = temp;
            left++;
            right--;
        }
    }

    //每次循环的步长为 2 * k
    public String reverseStr1(String s, int k) {
        char[] charArray = s.toCharArray();
        for (int i = 0; i < charArray.length; i += 2 * k) {
            int left = i;
            int right = Math.min(charArray.length-1, i + k - 1);
            while (left < right) {
                char temp = charArray[left];
                charArray[left] = charArray[right];
                charArray[right] = temp;
                left++;
                right--;
            }
        }
        return String.valueOf(charArray);
    }
}
